﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using XSTDZ.ERP.Infrastructure;
using System.Data;

namespace XSTDZ.ERP.WebApp.Models
{
    public class ExportToExcelModel
    {
        /// <summary>
        /// 导出数据到Excel
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="fileName">导出的文件名</param>
        /// <param name="titles">导出的列标题</param>
        /// <param name="dt">导出的数据表</param>
        public void CreateDataToExcel(HttpContextBase context,string fileName, string[] titles, DataTable dt)
        {
            string filename = string.Format("{0}.xls",fileName);
            context.Response.ContentType = "application/vnd.ms-excel";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            context.Response.Clear();

            InitializeWorkbook();
            GenerateData(titles, dt);
            GetExcelStream().WriteTo(context.Response.OutputStream);
            context.Response.End();
        }

        HSSFWorkbook hssfworkbook;

        MemoryStream GetExcelStream()
        {
            //Write the stream data of workbook to the root directory
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            return file;
        }

        void GenerateData(string[] titles, DataTable dt)
        {
            dt = dt ?? new DataTable();
            ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
             int len = titles.Length;
            #region Excel标题
             IRow rowTitle = sheet1.CreateRow(0);
             for (int j = 0; j < len; j++)
             {
                 rowTitle.CreateCell(j).SetCellValue(titles[j].ToString());
             }
            #endregion
             
            int x = 1;
            int rows = dt.Rows.Count;
            #region 数据行
            for (int i = 1; i <= rows; i++)
            {
                IRow row = sheet1.CreateRow(i);
                for (int j = 0; j <len; j++)
                {
                    row.CreateCell(j).SetCellValue(dt.Rows[i-1][j].ToString());
                }
            }
            #endregion
        }
        void InitializeWorkbook()
        {
            hssfworkbook = new HSSFWorkbook();

            ////create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = SystemConfig.SystemName;
            hssfworkbook.DocumentSummaryInformation = dsi;

            ////create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "报表导出功能";
            hssfworkbook.SummaryInformation = si;
        }
    }
}